using System;
using System.IO;
using log4net.Core;

namespace Quiki.DocumentGraphProcessors
{
    public class CopyLinkedFilesProcessor : IDocumentGraphProcessor
    {
        public CopyLinkedFilesProcessor(
            DocumentProcessorSettings settings,
            FileSet documentFiles,
            ILogger logger)
        {
            this.settings = settings;
            this.documentFiles = documentFiles;
            this.logger = logger;
        }

        public void Execute(DocumentGraph documentGraph)
        {
            foreach (string linkedFileName in settings.LinkedFiles)
            {
                if (Path.IsPathRooted(linkedFileName))
                    logger.Log(Level.Warn, "Linked file '{0}' cannot be copied. It has to be specified as a relative path", linkedFileName);
                else
                {
                    string fullLinkedFileName = Path.Combine(settings.InputDir, linkedFileName);

                    if (false == File.Exists (fullLinkedFileName))
                        logger.Log (Level.Warn, "Linked file '{0}' does not exist", fullLinkedFileName);
                    else
                    {
                        if (false == documentFiles.HasFile(linkedFileName))
                        {
                            string destinationFileName = Path.Combine(settings.OutputDir, linkedFileName);
                            Directory.CreateDirectory(Path.GetDirectoryName(destinationFileName));
                            File.Copy (fullLinkedFileName, destinationFileName, true);
                            documentFiles.RegisterFile(linkedFileName);

                            logger.Log (Level.Info, "Copied linked file '{0}'", fullLinkedFileName);
                        }
                    }
                }
            }
        }

        private readonly DocumentProcessorSettings settings;
        private readonly FileSet documentFiles;
        private readonly ILogger logger;
    }
}